#!/home/ubuntu/.virtualenvs/meiduo_mall/bin/python

import os

from django.conf import settings
from django.template import loader
from meiduo_mall.apps.goods.models import SKU

from meiduo_mall.apps.goods.utils import get_categories, get_breadcrumb

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "meiduo_mall.settings.dev")

import django
django.setup()


def generate_static_sku_detail_html(sku_id):
    """
    生成静态商品详情页面
    :param sku_id: 商品sku id
    """

    # 查询商品频道分类
    categories = get_categories()

    # 调用封装的函数, 根据 sku_id 获取对应的
    # 1. 类别( sku )
    # 2. 商品( goods )
    # 3. 商品规格( spec )
    # data = get_goods_and_spec(sku_id, request)
    sku = SKU.objects.get(id=sku_id)
    sku.images = sku.skuimage_set.all()

    # 面包屑导航信息中的频道
    goods = sku.goods

    # 构建当前商品的规格键

    sku_specs = sku.skuspecification_set.order_by('spec_id')

    sku_key = []
    for spec in sku_specs:
        sku_key.append(spec.option.id)

    # 获取当前商品的所有SKU
    skus = goods.sku_set.all()

    # 构建不同规格参数（选项）的sku字典
    # spec_sku_map = {
    #     (规格1参数id, 规格2参数id, 规格3参数id, ...): sku_id,
    #     (规格1参数id, 规格2参数id, 规格3参数id, ...): sku_id,
    #     ...
    # }

    spec_sku_map = {}
    for s in skus:
        # 获取sku的规格参数
        s_specs = s.skuspecification_set.order_by('spec_id')

        # 用于形成规格参数-sku字典的键
        key = []
        for spec in s_specs:
            key.append(spec.option.id)

        # 向规格参数-sku字典添加记录
        spec_sku_map[tuple(key)] = s.id

    # 获取当前商品的规格信息
    # specs = [
    #    {
    #        'name': '屏幕尺寸',
    #        'options': [
    #            {'value': '13.3寸', 'sku_id': xxx},
    #            {'value': '15.4寸', 'sku_id': xxx},
    #        ]
    #    },
    #    {
    #        'name': '颜色',
    #        'options': [
    #            {'value': '银色', 'sku_id': xxx},
    #            {'value': '黑色', 'sku_id': xxx}
    #        ]
    #    },
    #    ...
    # ]
    goods_specs = goods.goodsspecification_set.order_by('id')

    # 若当前sku的规格信息不完整,则不再继续
    if len(sku_key) < len(goods_specs):
        return
    for index, spec in enumerate(goods_specs):
        # 复制当前sku的规格键
        key = sku_key[:]

        # print(key)
        # 该规格的选项
        spec_options = spec.specificationoption_set.all()

        for option in spec_options:
            # 在规格参数sku字典中查找符合当前规格的sku
            key[index] = option.id
            option.sku_id = spec_sku_map.get(tuple(key))

        spec.spec_options = spec_options
    data = {
        'goods': goods,
        'goods_specs': goods_specs,
        'sku': sku
    }


    # 获取面包屑导航:
    breadcrumb = get_breadcrumb(data['goods'].category3)

    # 渲染页面
    context = {
        'categories': categories,
        'goods': data.get('goods'),
        'specs': data.get('goods_specs'),
        'sku': data.get('sku'),
        'breadcrumb': breadcrumb
    }

    # return render(request, 'detail.html', context)

    template = loader.get_template('detail.html')
    html_text = template.render(context)
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'detail/' + str(sku_id) + '.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)


if __name__ == '__main__':
    skus = SKU.objects.all()
    for sku in skus:
        print(sku.id)
        generate_static_sku_detail_html(sku.id)